<template>
  <div class="workflow-container">
    <div class="workflow-header">
      <a-button type="link" @click="goBack" class="back-btn">
        <ArrowLeftOutlined />
        返回应用市场
      </a-button>
      <h1>AI工作流生成器</h1>
      <p v-if="currentApp">基于应用：{{ currentApp.appName }}</p>
    </div>
    
    <div class="workflow-content">
      <a-row :gutter="24">
        <a-col :span="8">
          <a-card title="输入需求" class="input-card">
            <a-form layout="vertical">
              <a-form-item label="描述您想要生成的内容">
                <a-textarea
                  v-model:value="userMessage"
                  placeholder="请详细描述您想要生成的内容，例如：创建一本关于人工智能的技术书籍，包含基础概念、应用场景和未来发展趋势..."
                  :rows="8"
                  :maxlength="2000"
                  show-count
                />
              </a-form-item>
              
              <a-form-item>
                <a-space direction="vertical" style="width: 100%">
                  <a-button
                    type="primary"
                    size="large"
                    block
                    :loading="generating"
                    :disabled="!userMessage.trim()"
                    @click="handleGenerate"
                  >
                    <ThunderboltOutlined />
                    开始生成工作流
                  </a-button>
                  
                  <a-button
                    v-if="generateResult"
                    size="large"
                    block
                    @click="clearResult"
                  >
                    <ClearOutlined />
                    清空结果
                  </a-button>
                </a-space>
              </a-form-item>
            </a-form>
          </a-card>
        </a-col>
        
        <a-col :span="8">
          <a-card title="反馈优化" class="feedback-card">
            <a-form layout="vertical">
              <a-form-item label="对生成结果的反馈意见">
                <a-textarea
                  v-model:value="feedbackMessage"
                  placeholder="请输入您对生成结果的反馈意见，例如：需要增加更多技术细节、调整章节结构、修改写作风格等..."
                  :rows="8"
                  :maxlength="2000"
                  show-count
                />
              </a-form-item>
              
              <a-form-item>
                <a-space direction="vertical" style="width: 100%">
                  <a-button
                    type="primary"
                    size="large"
                    block
                    :loading="submittingFeedback"
                    :disabled="!feedbackMessage.trim()"
                    @click="handleFeedback"
                  >
                    <MessageOutlined />
                    提交反馈
                  </a-button>
                  
                  <a-button
                    size="large"
                    block
                    @click="clearFeedback"
                  >
                    <ClearOutlined />
                    清空反馈
                  </a-button>
                </a-space>
              </a-form-item>
            </a-form>
            
            <!-- 反馈结果显示区域 -->
            <div v-if="feedbackResult" class="feedback-result-display">
              <a-divider>反馈处理结果</a-divider>
              <div class="feedback-content">
                <pre v-if="typeof feedbackResult === 'string'">{{ feedbackResult }}</pre>
                <div v-else class="json-preview">
                  <pre>{{ JSON.stringify(feedbackResult, null, 2) }}</pre>
                </div>
              </div>
            </div>
          </a-card>
        </a-col>
        
        <a-col :span="8">
          <a-card title="生成结果" class="result-card">
            <!-- 流式消息展示区域 -->
            <div v-if="isStreamActive || streamMessages.length > 0" class="stream-section">
              <div class="stream-card">
                <div class="stream-header">
                  <h4>实时处理进度</h4>
                  <a-badge v-if="isStreamActive" status="processing" text="处理中" />
                  <a-badge v-else status="success" text="已完成" />
                </div>
                <div class="stream-messages" ref="streamContainer">
                  <div
                    v-for="(msg, index) in streamMessages"
                    :key="index"
                    :class="['stream-message', `message-${msg.type}`]"
                  >
                    <div class="message-header">
                      <span class="node-name">{{ getNodeDisplayName(msg.node) }}</span>
                      <span class="timestamp">{{ formatTime(msg.timestamp) }}</span>
                    </div>
                    <div class="message-content">
                      <pre v-if="msg.type === 'streaming' || msg.type === 'chunk'">{{ msg.message }}</pre>
                      <div v-else>{{ msg.message }}</div>
                    </div>
                    <div v-if="isStreamActive && index === streamMessages.length - 1 && (msg.type === 'streaming' || msg.type === 'chunk')" class="processing-indicator">
                      <span class="dot"></span>
                      <span class="dot"></span>
                      <span class="dot"></span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <div v-if="!generateResult && !generating && !isStreamActive && streamMessages.length === 0" class="empty-result">
              <a-empty description="请输入需求并点击生成按钮">
                <template #image>
                  <BookOutlined style="font-size: 64px; color: #ccc;" />
                </template>
              </a-empty>
            </div>
            
            <a-spin :spinning="generating" tip="AI工作流正在生成内容，请稍候...">
              <div v-if="generateResult" class="result-content">
                <div class="result-header">
                  <h3>生成成功！</h3>
                  <a-space>
                    <a-button @click="copyResult">
                      <CopyOutlined />
                      复制结果
                    </a-button>
                    <a-button type="primary" @click="downloadResult">
                      <DownloadOutlined />
                      下载文件
                    </a-button>
                  </a-space>
                </div>
                
                <div class="result-display">
                  <a-tabs v-model:activeKey="activeTab">
                    <a-tab-pane key="preview" tab="预览">
                      <div class="content-preview">
                        <pre v-if="typeof generateResult === 'string'">{{ generateResult }}</pre>
                        <div v-else class="json-preview">
                          <pre>{{ JSON.stringify(generateResult, null, 2) }}</pre>
                        </div>
                      </div>
                    </a-tab-pane>
                    <a-tab-pane key="raw" tab="原始数据">
                      <div class="raw-data">
                        <pre>{{ JSON.stringify(generateResult, null, 2) }}</pre>
                      </div>
                    </a-tab-pane>
                  </a-tabs>
                </div>
              </div>
            </a-spin>
          </a-card>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  ArrowLeftOutlined,
  ThunderboltOutlined,
  CopyOutlined,
  DownloadOutlined,
  ClearOutlined,
  BookOutlined,
  MessageOutlined
} from '@ant-design/icons-vue'
import { preChat } from '@/api/app'
import { workFlow, feedback } from '@/api/ai'
import type { App } from '@/types/api'
import { getToken } from '@/utils/auth'
import { EventSourcePolyfill } from 'event-source-polyfill'

// SSE流式消息接口定义
interface StreamMessage {
  node: string
  type: 'start' | 'streaming' | 'chunk' | 'complete' | 'success' | 'error' | 'workflow_complete' | 'info'
  message: string
  timestamp: number
  data?: any
  chunk?: string
}

const route = useRoute()
const router = useRouter()

const currentApp = ref<App | null>(null)
const userMessage = ref('')
const generating = ref(false)
const generateResult = ref<any>(null)
const activeTab = ref('preview')
const feedbackMessage = ref('')
const submittingFeedback = ref(false)
const feedbackResult = ref<any>(null)

// SSE流式消息相关状态
const streamMessages = ref<StreamMessage[]>([])
const isStreamActive = ref(false)
const eventSource = ref<EventSourcePolyfill | null>(null)

const goBack = () => {
  router.push('/app-market')
}

const handleGenerate = async () => {
  if (!userMessage.value.trim()) {
    message.warning('请输入内容需求描述')
    return
  }
  
  if (userMessage.value.length > 2000) {
    message.warning('输入内容不能超过2000字')
    return
  }
  
  // 直接启动SSE流式处理
  startStream(userMessage.value)
}

// SSE流式消息处理函数
const startStream = (userInput: string) => {
  if (eventSource.value) {
    eventSource.value.close()
    eventSource.value = null
  }
  
  streamMessages.value = []
  isStreamActive.value = true
  generating.value = true
  
  try {
    const token = getToken()
    if (!token) {
      message.error('请先登录')
      return
    }
    
    // 使用正确的API路径
    const url = `/api/ai/streamflow?generateFullBookRequest=${encodeURIComponent(userInput)}`
    
    eventSource.value = new EventSourcePolyfill(url, {
      heartbeatTimeout: 3 * 60 * 1000,
      headers: {
        Authorization: 'Bearer ' + token,
        Accept: 'text/event-stream'
      },
      withCredentials: true,
    })
    
    eventSource.value.onopen = function (e) {
      console.log('SSE连接已建立', e)
    }
    
    eventSource.value.onmessage = (event) => {
      handleStreamMessage(event.data)
    }
    
    eventSource.value.onerror = (event) => {
      console.error('SSE连接出错：', event)
      isStreamActive.value = false
      generating.value = false
      message.error('连接中断，请重试')
      if (eventSource.value) {
        eventSource.value.close()
        eventSource.value = null
      }
    }
  } catch (error) {
    console.error('启动SSE连接失败:', error)
    isStreamActive.value = false
    generating.value = false
    message.error('启动连接失败')
  }
}

const handleStreamMessage = (data: string) => {
  try {
    const message = JSON.parse(data)
    
    switch (message.type) {
      case 'start':
        streamMessages.value.push({
          node: message.node || 'system',
          type: 'start',
          message: message.message || '开始处理...',
          timestamp: Date.now()
        })
        break
        
      case 'streaming':
      case 'chunk':
        const lastMessage = streamMessages.value[streamMessages.value.length - 1]
        if (lastMessage && lastMessage.node === message.node && 
            (lastMessage.type === 'streaming' || lastMessage.type === 'chunk')) {
          lastMessage.message += message.chunk || message.message || ''
        } else {
          streamMessages.value.push({
            node: message.node || 'system',
            type: 'streaming',
            message: message.chunk || message.message || '',
            timestamp: Date.now()
          })
        }
        break
        
      case 'complete':
      case 'success':
        streamMessages.value.push({
          node: message.node || 'system',
          type: 'complete',
          message: message.message || '处理完成',
          timestamp: Date.now(),
          data: message.data
        })
        
        // 如果是工作流整体完成（没有具体节点名称），则关闭生成状态
        if (!message.node || message.message === '工作流执行完成') {
          isStreamActive.value = false
          generating.value = false
          stopStream()
          
          // 设置生成结果
          if (message.data) {
            generateResult.value = message.data
          }
        }
        break
        
      case 'error':
        streamMessages.value.push({
          node: message.node || 'system',
          type: 'error',
          message: message.message || '处理出错',
          timestamp: Date.now()
        })
        break
        
      case 'workflow_complete':
        streamMessages.value.push({
          node: message.node || 'system',
          type: 'workflow_complete',
          message: message.message || '工作流生成完成',
          timestamp: Date.now(),
          data: message.data
        })
        
        // 设置生成结果
        if (message.data) {
          generateResult.value = message.data
        }
        
        isStreamActive.value = false
        generating.value = false
        stopStream()
        break
        
      default:
        streamMessages.value.push({
          node: message.node || 'system',
          type: 'info',
          message: message.message || data,
          timestamp: Date.now()
        })
    }
    
    // 自动滚动到最新消息
    nextTick(() => {
      const streamContainer = document.querySelector('.stream-messages')
      if (streamContainer) {
        streamContainer.scrollTop = streamContainer.scrollHeight
      }
    })
    
  } catch (error) {
    console.error('解析消息失败:', error)
    streamMessages.value.push({
      node: 'system',
      type: 'error',
      message: '消息解析失败: ' + data,
      timestamp: Date.now()
    })
  }
}

const stopStream = () => {
  if (eventSource.value) {
    eventSource.value.close()
    eventSource.value = null
  }
  isStreamActive.value = false
  generating.value = false
}

const getNodeDisplayName = (node: string): string => {
  const nodeNames: Record<string, string> = {
    'system': '系统',
    'workflow': '工作流',
    'start': '开始',
    'end': '结束',
    'process': '处理',
    'generate': '生成',
    'validate': '验证',
    'fix': '修复',
    'feedback': '反馈',
    'complete': '完成'
  }
  return nodeNames[node] || node
}

const formatTime = (timestamp: number): string => {
  return new Date(timestamp).toLocaleTimeString()
}

const copyResult = async () => {
  try {
    const textToCopy = typeof generateResult.value === 'string' 
      ? generateResult.value 
      : JSON.stringify(generateResult.value, null, 2)
    await navigator.clipboard.writeText(textToCopy)
    message.success('结果已复制到剪贴板')
  } catch (error) {
    message.error('复制失败')
  }
}

const downloadResult = () => {
  const content = typeof generateResult.value === 'string' 
    ? generateResult.value 
    : JSON.stringify(generateResult.value, null, 2)
  const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `workflow-result-${Date.now()}.txt`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
  message.success('文件下载成功')
}

const clearResult = () => {
  generateResult.value = null
  feedbackResult.value = null
  feedbackMessage.value = ''
  activeTab.value = 'preview'
}

const handleFeedback = async () => {
  if (!feedbackMessage.value.trim()) {
    message.warning('请输入反馈意见')
    return
  }
  
  if (feedbackMessage.value.length > 2000) {
    message.warning('反馈内容不能超过2000字')
    return
  }
  
  // 启动反馈流式处理
  startFeedbackStream(feedbackMessage.value)
}

// 反馈流式处理函数 - 复用现有的 workflow 处理逻辑
const startFeedbackStream = (feedbackInput: string) => {
  if (eventSource.value) {
    eventSource.value.close()
    eventSource.value = null
  }
  
  // 清空之前的反馈结果，但保留流式消息
  feedbackResult.value = null
  submittingFeedback.value = true
  isStreamActive.value = true
  
  try {
    const token = getToken()
    if (!token) {
      message.error('请先登录')
      submittingFeedback.value = false
      isStreamActive.value = false
      return
    }
    
    // 使用 feedback API 的 GET 方法
    const url = `/api/ai/feedback?feedback=${encodeURIComponent(feedbackInput)}`
    
    eventSource.value = new EventSourcePolyfill(url, {
      heartbeatTimeout: 3 * 60 * 1000,
      headers: {
        Authorization: 'Bearer ' + token,
        Accept: 'text/event-stream'
      },
      withCredentials: true,
    })
    
    eventSource.value.onopen = function (e) {
      console.log('反馈SSE连接已建立', e)
    }
    
    // 复用现有的 handleStreamMessage 方法
    eventSource.value.onmessage = (event) => {
      handleStreamMessage(event.data)
      
      // 检查是否是反馈完成消息，如果是则停止反馈状态
      try {
        const message = JSON.parse(event.data)
        if (message.type === 'complete' || message.type === 'success' || 
            message.type === 'workflow_complete' || message.message === '工作流执行完成') {
          submittingFeedback.value = false
          
          // 设置反馈结果
          if (message.data) {
            feedbackResult.value = message.data
          }
        } else if (message.type === 'error') {
          submittingFeedback.value = false
        }
      } catch (error) {
        // 忽略解析错误，让 handleStreamMessage 处理
      }
    }
    
    eventSource.value.onerror = (event) => {
      console.error('反馈SSE连接出错：', event)
      submittingFeedback.value = false
      isStreamActive.value = false
      message.error('反馈连接中断，请重试')
      if (eventSource.value) {
        eventSource.value.close()
        eventSource.value = null
      }
    }
  } catch (error) {
    console.error('启动反馈SSE连接失败:', error)
    submittingFeedback.value = false
    isStreamActive.value = false
    message.error('启动反馈连接失败')
  }
}

const clearFeedback = () => {
  feedbackMessage.value = ''
  feedbackResult.value = null
}

const initPreChat = async () => {
  const appId = route.query.appId as string
  if (appId) {
    try {
      const response = await preChat(Number(appId))
      if (response.code === 0) {
        userMessage.value = response.data || ''
      }
    } catch (error) {
      console.error('获取预聊天内容失败:', error)
    }
  }
  
  // 从路由参数获取应用信息
  if (route.query.app) {
    try {
      currentApp.value = JSON.parse(route.query.app as string)
    } catch (error) {
      console.error('解析应用信息失败:', error)
    }
  }
}

onMounted(() => {
  initPreChat()
})

onUnmounted(() => {
  stopStream()
})
</script>

<style scoped>
.workflow-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 24px;
}

.workflow-header {
  text-align: center;
  margin-bottom: 32px;
  color: white;
}

.back-btn {
  position: absolute;
  left: 24px;
  top: 24px;
  color: white;
}

.workflow-header h1 {
  font-size: 36px;
  margin: 0 0 8px 0;
  color: white;
}

.workflow-content {
  max-width: 1400px;
  margin: 0 auto;
}

.input-card,
.feedback-card,
.result-card {
  height: 700px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.empty-result {
  height: 500px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.result-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.result-display {
  flex: 1;
  overflow: hidden;
}

.content-preview,
.raw-data {
  height: 500px;
  overflow: auto;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
}

.content-preview pre,
.raw-data pre,
.json-preview pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  line-height: 1.5;
}

.json-preview {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
}

.feedback-panel {
  height: 500px;
  overflow: auto;
  padding: 16px;
}

.feedback-form {
  margin-bottom: 24px;
}

.feedback-result {
  margin-top: 16px;
}

.feedback-content {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  max-height: 200px;
  overflow: auto;
}

.feedback-content pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  line-height: 1.5;
}

.feedback-result-display {
  margin-top: 16px;
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
}

.feedback-card .ant-card-body {
  height: calc(100% - 57px);
  overflow: auto;
}

/* 流式消息样式 */
.stream-section {
  margin-bottom: 20px;
}

.stream-card {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  overflow: hidden;
}

.stream-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #fafafa;
  border-bottom: 1px solid #e8e8e8;
}

.stream-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
}

.stream-messages {
  max-height: 400px;
  overflow-y: auto;
  padding: 8px;
}

.stream-message {
  margin-bottom: 12px;
  padding: 12px;
  border-radius: 6px;
  border-left: 4px solid #d9d9d9;
  background: #fafafa;
  transition: all 0.3s ease;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.node-name {
  font-weight: 600;
  font-size: 12px;
  color: #666;
}

.timestamp {
  font-size: 11px;
  color: #999;
}

.message-content {
  font-size: 13px;
  line-height: 1.5;
  color: #333;
}

.message-content pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  background: transparent;
  padding: 0;
}

/* 不同消息类型的样式 */
.message-start {
  border-left-color: #52c41a;
  background: #f6ffed;
}

.message-streaming,
.message-chunk {
  border-left-color: #1890ff;
  background: #e6f7ff;
  animation: pulse 2s infinite;
}

.message-complete,
.message-success {
  border-left-color: #52c41a;
  background: #f6ffed;
}

.message-error {
  border-left-color: #ff4d4f;
  background: #fff2f0;
}

.message-workflow_complete {
  border-left-color: #722ed1;
  background: #f9f0ff;
}

.message-info {
  border-left-color: #faad14;
  background: #fffbe6;
}

/* 处理中指示器 */
.processing-indicator {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 8px;
  gap: 4px;
}

.processing-indicator .dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #1890ff;
  animation: bounce 1.4s infinite ease-in-out both;
}

.processing-indicator .dot:nth-child(1) {
  animation-delay: -0.32s;
}

.processing-indicator .dot:nth-child(2) {
  animation-delay: -0.16s;
}

/* 动画效果 */
@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.02);
  }
  100% {
    transform: scale(1);
  }
}

@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}
</style>